using System.Collections.Specialized;
using System.ComponentModel.Design;
using Microsoft.Practices.Common;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Library;

namespace PrismFactory.SoftwareFactory.Extensions.ValueProviders
{
    public class IsValidExpressionProvider : ValueProvider, IAttributesConfigurable
    {
        public const string ValueExpressionAttribute = "ValueExpression";

        private string valueExpression;

        public override bool OnBeginRecipe(object currentValue, out object newValue)
        {
            if (string.IsNullOrEmpty(currentValue as string))
            {
                bool expressionIsValid = Evaluate();
                newValue = expressionIsValid;
                return true;
            }
            newValue = null;
            return false;
        }

        private bool Evaluate()
        {
            var evaluator = new ExpressionEvaluationService();
            var dictservice = (IDictionaryService) GetService(typeof (IDictionaryService));

            object value = null;

            try
            {
                value = evaluator.Evaluate(valueExpression, new ServiceAdapterDictionary(dictservice)).ToString();
            }
            catch
            {
            }

            bool expressionIsValid = (value != null);
            return expressionIsValid;
        }

        public override bool OnArgumentChanged(string changedArgumentName, object changedArgumentValue, object currentValue, out object newValue)
        {
            bool expressionIsValid = Evaluate();
            newValue = expressionIsValid;
            return true;
        }

        public void Configure(StringDictionary attributes)
        {
            if (attributes.ContainsKey(ValueExpressionAttribute))
            {
                valueExpression = attributes[ValueExpressionAttribute];
            }
        }
    }
}